import transmission_rpc as transmissionrpc
import time
import logging
from configobj import ConfigObj

cfg = ConfigObj("config.ini")

HASH_FILE = cfg['HASH_FILE']
LOG_FILE = cfg['LOG_FILE']
delData = cfg['DELETE_DATA']
keepForDays = float(cfg['SEED_FOR'])

conn = cfg['connection']
TRANS_HOST = conn['TRANS_HOST']
TRANS_PORT = conn['TRANS_PORT']
TRANS_USER = conn['TRANS_USER']
TRANS_PASS = conn['TRANS_PASS']
TRANS_PATH = conn['TRANS_PATH']


def loadHashesFromFile(infile):
    '''Loads hashes from a file.  These hashes will be for torrents to
       ignore for removal. (they will not be tested for age or removed)
       takes a string for a filename as argument, return a list.
    '''
    inFile = open(infile, mode='r', encoding='utf-8')
    all = [line.rstrip() for line in inFile.readlines()]
    hashes = []
    for line in all:
        hashes.append(line)
    return hashes


def mkTime(seconds):
    '''Takes int seconds and returns a str of HH:MM:SS
    '''
    hours = seconds // 3600
    tmp = seconds - (hours * 3600)
    minutes = tmp // 60
    seconds = tmp - (minutes * 60)
    return '%02d:%02d:%02d' % (hours, minutes, seconds)


logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M', filename=LOG_FILE,
                    level=logging.INFO)

tc = transmissionrpc.Client(host=TRANS_HOST, port=TRANS_PORT, username=TRANS_USER, password=TRANS_PASS, path=TRANS_PATH)
print('start success')
while True:
    try:
        keep_hashes = loadHashesFromFile(HASH_FILE)

        # all_hashes = [torrent.hashString.encode('ascii', 'ignore') for torrent in tc.get_torrents()]
        all_hashes = [torrent.hashString for torrent in tc.get_torrents()]

        del_hashes = [x for x in all_hashes if x not in keep_hashes]

        keepForSecs = int(keepForDays * 86400)  # don't change this.

        for torrent in tc.get_torrents(del_hashes):
            if not torrent.seeding:
                continue
            if torrent.done_date.timestamp() == 0:
                continue

            delDate = torrent.done_date.timestamp() + keepForSecs
            now = int(time.time())
            age = mkTime(now - torrent.done_date.timestamp())
            if now > delDate:
                logging.info('    remover       external        Seeded for %s, removing torrent %s', age, torrent.name)
                tc.remove_torrent(torrent.hashString, delData)

    except Exception as e:
        logging.error('        error       %s', str(e))
    time.sleep(1200)
